import{ defineStore }from'pinia'
import type {
  MessageOptions, MessageResult
} from 'wot-design-uni/components/wd-message-box/types'
import { getCurrentPath, merge} from "@/utils"

export type GlobalMessageOptions = MessageOptions & {
  success?: (res: MessageResult) => void
  fail?: (res: MessageResult) => void
}

interface GlobalMessage {
  messageOptions: GlobalMessageOptions | null
  currentPage: string
  currentKey: number
}


export const useGlobalMessage = defineStore('global-message', {
  state: (): GlobalMessage =>({
    messageOptions: null,
    currentPage:'',
    currentKey: 0
  }),
  actions: {
    show(options: GlobalMessageOptions) {
      // @ts-ignore
      this.currentPage= getCurrentPath()
      this.messageOptions = options
      this.currentKey++;
    },
    alert(title: string, options?: GlobalMessageOptions) {
      const messageOptions = { title, type: 'alert', showCancelButton: false } as GlobalMessageOptions
      this.show(merge(messageOptions, {...options}))
    },
    confirm(title: string, options?: GlobalMessageOptions ) {
      const messageOptions = {
        title,
        type: 'confirm',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        showCancelButton: true,
      } as GlobalMessageOptions
      this.show(merge(messageOptions, {...options}))
    },
    prompt(title: string, options?: GlobalMessageOptions) {
      const messageOptions = {
        title,
        type: 'prompt',
        confirmButtonText: '提交',
        cancelButtonText: '关闭',
        showCancelButton: true,
      } as GlobalMessageOptions;
      this.show(merge(messageOptions, {...options}))
    },
    // 关闭 Toast
    close() {
      this.messageOptions = null
      this.currentPage = ''
      this.currentKey = -1;
    },
  },
})

export declare type MessageUtil = ReturnType<typeof useGlobalMessage>